package taskhook

import (
	"fmt"
	"github.com/robfig/cron/v3"
	"gitlab.local/golibrary/utils"
	"sync"
	"time"
)

func (h *HookService) Persistence() {
	if h.running {
		return
	}
	h.running = true
	defer func() {
		h.running = false
	}()
	list := h.list
	if len(list) == 0 {
		return
	}
	wg := sync.WaitGroup{}
	wg.Add(len(list))
	for _, v := range list {
		go func(hook TaskHook) {
			hook.Fn()
			wg.Done()
		}(v)
	}
	wg.Wait()
	return
}

func (h *HookService) Stop() {
	if h.job != nil {
		h.job.Stop()
	}
}

func (h *HookService) Reload() {
	zone := h.loadTimeZone()
	server := h.loadTimeServer()
	if h.prevZone == zone && h.prevServer == server {
		return
	}
	h.prevZone = zone
	h.prevServer = server
	h.Stop()
	nyc, _ := time.LoadLocation(zone)
	h.job = cron.New(cron.WithLocation(nyc))
	spec := "0 12 * * ?"
	_, _ = h.job.AddFunc(spec, func() {
		_, _ = utils.ShellWithString(fmt.Sprintf("ntpdate -b %s", server))
	})
	_, _ = h.job.AddFunc(spec, h.Persistence)
	//增加额外任务...
	h.mapLock.Lock()
	for _, v := range h.extTask {
		if v.Spec == "" {
			continue
		}
		v.EntryID, _ = h.job.AddFunc(v.Spec, v.Fn)
	}
	h.mapLock.Unlock()
	h.job.Start()
}

func (h *HookService) loadTimeZone() string {
	zone, _ := h.config.GetString("timezone_php")
	if zone == "" {
		zone = "Local"
	}
	return zone
}

func (h *HookService) loadTimeServer() string {
	server, _ := h.config.GetString("timeserver")
	if server == "" {
		server = "pool.ntp.org"
	}
	return server
}
